import { createReducer, createAsyncAction } from 'redux-action-tools';
import axios from 'axios'
const appInstance = axios.create({
  baseURL: 'http://localhost:5000/',
  timeout: 1000,
  headers: {
    'authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjU3ZmNhODc3NTIxNDA1MjM5NDJjNmU0NSIsImlhdCI6MTQ4MTg1NDE4Mn0.oP_2Vd2C22aEN6Xp0qI5Hs92HXsNasPCuKPlr4ZAKhQ',
     "accept": "application/json"
  }
});
// ------------------------------------
// 这里为所有跟答题期数有关热reducer
// ------------------------------------


const GETQUESTIONSBYTERMSID = 'GETQUESTIONSBYTERMSID',
      GETONETERMBYID = 'GETONETERMBYID',
      ADDONEQUESTION='ADDONEQUESTION',
      UPDATEONEQUESTIONBYID = 'UPDATEONEQUESTIONBYID',
      DELETEONEQUESTIONBYID = 'DELETEONEQUESTIONBYID';

export const getQuestionsByTermsId = createAsyncAction(GETQUESTIONSBYTERMSID, (id) => {
  // console.log(id)
  return appInstance.get(`/questions/${id}`).then(response=>Promise.resolve(response.data))

})
const GETQUESTIONSBYTERMSID_SUCCESS = (state, action) => {
  // console.log(state,action);
  let questionsList=action.payload.data;

  return Object.assign({}, state, { questionList:  questionsList.map(question=>{
    question.key=question._id;
    return question;
  }) ,questionFetching:false})
}


export const getOneTermByID = createAsyncAction(GETONETERMBYID, (id) => {
  return appInstance.get(`/questions/${id}`).then(response=>Promise.resolve(response.data))
})

const GETONETERMBYID_SUCCESS = (state, action) => {
  const answerlist = action.payload.data;
  return Object.assign({}, state,  { answerlist: answerlist ,questionFetching:false})
}

export const updateOneQuestionById = createAsyncAction(UPDATEONEQUESTIONBYID, (question) => {

  return appInstance.put(`/questions/${question._id}`,{question:question}).then(response=>Promise.resolve(question))

})
const UPDATEONEQUESTIONBYID_SUCCESS = (state, action) => {
  let newterm=action.payload;
  newterm.key=newterm._id;
  // console.log(newterm)
   return Object.assign({}, state,  { questionList: state.questionList.map(term=>{
      if(newterm._id===term._id){
        // console.log(newterm,term)
        return newterm
      }else{
      return term
        
      }
   }) ,questionFetching:false});
}


export const deleteOneQuestionById = createAsyncAction(DELETEONEQUESTIONBYID, (termId) => {
  console.log(termId);
  return appInstance.delete(`/questions/${termId}`).then(response=>Promise.resolve(response.data))

})
const DELETEONEQUESTIONBYID_SUCCESS = (state, action) => {
  // console.log("请求成功了",action);

  let questionList=state.questionList.filter(term=>{
    return term._id!==action.payload.data._id;
  });
   return Object.assign({}, state, { questionList:questionList ,questionFetching:false})
}


export const addOneQuestion = createAsyncAction(ADDONEQUESTION, (question) => {

   return appInstance.post(`/questions`,{question:question}).then(response=>Promise.resolve(response.data))

})
const ADDONEQUESTION_SUCCESS = (state, action) => {
  console.log("请求成功了",action.payload);
  let newQuestion=Object.assign({},action.payload.data,{key:action.payload.data._id});
  return Object.assign({}, state, { questionList:[  newQuestion,...state.questionList],questionFetching:false})
}



const getError = (state, action) => {
  console.log("请求失败了");
  return Object.assign({},state,{fetchError:true})
}

const questionFetchingHandler=(state,action)=>{
  return Object.assign({},state,{questionFetching:true})
}

const questionListReducer = createReducer()
  .when(GETQUESTIONSBYTERMSID,questionFetchingHandler)
  .done(GETQUESTIONSBYTERMSID_SUCCESS)
  .when(UPDATEONEQUESTIONBYID,questionFetchingHandler)
  .done(UPDATEONEQUESTIONBYID_SUCCESS)
  .when(GETONETERMBYID,questionFetchingHandler)
  .done(GETONETERMBYID_SUCCESS)
  .when(ADDONEQUESTION,questionFetchingHandler)
  .done(ADDONEQUESTION_SUCCESS)
  .when(DELETEONEQUESTIONBYID,questionFetchingHandler)
  .done(DELETEONEQUESTIONBYID_SUCCESS)
  .failed(getError)
  .build({ questionList: [],questionFetching:true,fetchError:false });

export default questionListReducer


